<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2022-2099 李志刚（854378082@qq.com）
 * @Date: 2019-01-03 20:14:16
 * @Description: 部门管理
 * @LastEditors: 李志刚
 * @LastEditTime: 2022-05-05 21:28:12
 * @FilePath: /CoinCMF/app/Http/Controllers/Console/Rbac/DepartmentController.php
 */

namespace App\Http\Controllers\Console\Rbac;

use App\Customize\Func;
use App\Models\Rbac\Admin;
use App\Models\Rbac\Department;
use Illuminate\Support\Facades\DB;
use App\Exceptions\FireFlyException;
use App\Http\Controllers\Controller;
use App\Http\Requests\DetailRequest;
use App\Http\Requests\StatusRequest;
use App\Models\Rbac\DepartmentAdmin;
use App\Http\Requests\Ums\DepartmentRequest;
use App\Http\Requests\Ums\DepartmentAdminRequest;
use App\Http\Requests\Ums\DepartmentUpdateRequest;

class DepartmentController extends Controller
{
    public function getList()
    {
        $all = Department::select('id', 'name','parent_id')->where('status', 1)->where('del_flag', 0)->orderBy('id', 'asc')->get();
        $res = Func::toTreeSelect($all->toArray());
        return $this->resJson(200, '成功', $res);
    }
    public function getTree()
    {
        $all = Department::select('id', 'parent_id', 'name', 'status')->where('del_flag', 0)->orderBy('id', 'asc')->get();
        $tree = $this->toTree($all, 0);
        return $this->resJson(200, '成功', $tree);
    }
    private function toTree($data, $pid)
    {
        $tree = [];
        if ($data->count() > 0) {
            foreach ($data as $v) {
                if ($v->parent_id == $pid) {
                    $v = ['department_id' => $v->id, 'title' => $v->name, 'status' => $v->status, '_showChildren' => true];
                    $v['children'] = $this->toTree($data, $v['department_id']);
                    $tree[] = $v;
                }
            }
        }
        return $tree;
    }
    public function getSelect()
    {
        $department = Department::select('id', 'parent_id', 'name')->where('del_flag', 0)->orderBy('id', 'asc')->get();
        $select = Func::toTreeSelect($department->toArray());
        $result[] = ['id' => 0,'parent_id' => 0,'title' => "一级部门",'value'=>0,'expand'=>true,'selected'=>false,'checked'=>false];
        $result = array_merge($result,$select);
        return $this->resJson(200, '成功', $result);
    }
    public function postCreate(DepartmentRequest $request)
    {
        $data = $request->all();
        Department::create(['parent_id' => $data['parent_id'], 'name' => $data['name'], 'status' => $data['status']]);
        return $this->resJson(200,'成功');
    }
    public function postEdit(DepartmentUpdateRequest $request)
    {
        $data = $request->all();
        if($data['detail_id'] == $data['parent_id']){
            throw new FireFlyException(400,"父级不能是自己");
        }
        Department::where('id', $data['detail_id'])->update(['parent_id' => $data['parent_id'], 'name'=> $data['name'],'status'=>$data['status']]);
        return $this->resJson(200,'成功');
    }
    public function postStatus(StatusRequest $request)
    {
        $data = $request->all();
        Department::where('id',$data['detail_id'])->update(['status'=>$data['status']]);
        return $this->resJson(200,'成功');
    }
    public function getDetail(DetailRequest $request)
    {
        $detail = Department::findOrFail($request->input('detail_id'));
        return $this->resJson(200, '成功', $detail);
    }
    public function postRemove(DetailRequest $request)
    {
        $detail_id = $request->input('detail_id');
        $arr = DB::select("SELECT t2.id as id FROM (SELECT @r AS _ids, (SELECT @r := GROUP_CONCAT(id) FROM ums_department WHERE FIND_IN_SET(parent_id,@r)) AS id FROM (SELECT @r := ".$detail_id.") vars NATURAL JOIN ums_department h WHERE @r IS NOT NULL) t1,ums_department t2 WHERE FIND_IN_SET(t2.id,t1._ids)");
        $ids = array_map(function($q){
            return $q->id;
        },$arr);
        // 查询下属用户
        if(DepartmentAdmin::whereIn('department_id', $ids)->count() > 0)
        {
            throw new FireFlyException(403,'部门下有用户');
        }
        Department::whereIn('id',$ids)->update(['del_flag'=>1]);
        return $this->resJson(200,'成功');
    }
    public function postAdminList(DetailRequest $request)
    {
        $admin_ids = DepartmentAdmin::where('department_id', $request->input('detail_id'))->pluck('admin_id');
        $list = Admin::whereIn('id', $admin_ids)->orderBy('id', 'asc')->get();
        return $this->resJson(200, '成功', $list);
    }
    public function postRemoveAdmin(DepartmentAdminRequest $request)
    {
        DepartmentAdmin::where('department_id', $request->input('detail_id'))->where('admin_id', $request->input('admin_id'))->delete();
        return $this->resJson(200, '成功');
    }
}
